package cn.kys.common.utils;


import freemarker.template.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import static freemarker.template.Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS;

/**
 * @author ME
 * @date 2019/08/24
 */

public class ExportWordUtil {
    private Configuration config;


    public static SimpleDateFormat sdf_dx = new SimpleDateFormat("yyyy-MM-dd");

    public static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");

    public ExportWordUtil() {
        config = new Configuration(DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
        config.setDefaultEncoding("utf-8");
        
        
    }

    /**
     * FreeMarker生成Word
     * @param dataMap 数据
     * @param templateName 模板名
     * @param response HttpServletResponse
     * @param fileName 导出的word文件名
     */
    public void exportWord(Map<String, Object> dataMap, String templateName, HttpServletResponse response, String fileName) {
        //加载模板(路径)数据，也可使用setServletContextForTemplateLoading()方法放入到web文件夹下
        config.setClassForTemplateLoading(this.getClass(), "/templates");
        //设置异常处理器 这样的话 即使没有属性也不会出错 如：${list.name}...不会报错
        config.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
        config.setDefaultEncoding("UTF-8");
        try {
            if(templateName.endsWith(".ftl")) {
                templateName = templateName.substring(0, templateName.indexOf(".ftl"));
            }
            Template template = config.getTemplate(templateName + ".ftl");
            response.setContentType("application/msword");
            response.setHeader("Content-disposition", "attachment;filename="+ URLEncoder.encode(fileName, "utf-8"));
             
            OutputStream outputStream = response.getOutputStream();
            Writer out = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));

            //将模板中的预先的代码替换为数据
            template.process(dataMap, out);
            
            
            System.out.println();
            System.out.println("由模板文件：" + templateName + ".ftl" + " 生成Word文件 " + fileName + " 成功！！");
            out.flush();
            

        } catch (TemplateNotFoundException e) {
        	  System.out.println("模板文件未找到");
            e.printStackTrace();
        } catch (MalformedTemplateNameException e) {
        	  System.out.println("模板类型不正确");
            e.printStackTrace();
        } catch (TemplateException e) {
        	  System.out.println("填充模板时异常");
            e.printStackTrace();
        } catch (IOException e) {
        	  System.out.println("IO异常");
            e.printStackTrace();
        }
    }

    /**
     * FreeMarker生成Word
     * @param dataMap 数据
     * @param templateName 模板名
     * @param response HttpServletResponse
     * @param fileName 导出的word文件名
     */
    public void exportWordToLocal(Map<String, Object> dataMap, String templateName, String filePath,String fileName) {
        //加载模板(路径)数据，也可使用setServletContextForTemplateLoading()方法放入到web文件夹下
        config.setClassForTemplateLoading(this.getClass(), "/templates");
        //设置异常处理器 这样的话 即使没有属性也不会出错 如：${list.name}...不会报错
        config.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
        config.setDefaultEncoding("UTF-8");
        try {
            if(templateName.endsWith(".ftl")) {
                templateName = templateName.substring(0, templateName.indexOf(".ftl"));
            }
            Template template = config.getTemplate(templateName + ".ftl");
            File outFile = null;

            //创建一个文件路径，用来存放生成的相关文件

            File myFilePath=new File(filePath);
            if(!myFilePath.exists()){
               myFilePath.mkdir();
            }

            //创建新文件

            template = config.getTemplate(templateName + ".ftl","UTF-8");
            outFile=new File(myFilePath+"/"+fileName);

            Writer out = null;
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
            // 生成文件
            template.process(dataMap, out);


            System.out.println("由模板文件：" + templateName + ".ftl" + " 生成Word文件 " + fileName + " 成功！！");
            out.flush();
            out.close();

        } catch (TemplateNotFoundException e) {
            System.out.println("模板文件未找到");
            e.printStackTrace();
        } catch (MalformedTemplateNameException e) {
            System.out.println("模板类型不正确");
            e.printStackTrace();
        } catch (TemplateException e) {
            System.out.println("填充模板时异常");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("IO异常");
            e.printStackTrace();
        }
    }

    /**
     * FreeMarker生成Word
     * @param dataMap 数据
     * @param templateName 模板名
     * @param response HttpServletResponse
     * @param fileName 导出的word文件名
     */
    public void exportWordToLocalPDF(HttpServletRequest request, HttpServletResponse response,Map<String, Object> dataMap, String templateName, String filePath, String fileName,String pdfName) {
        //加载模板(路径)数据，也可使用setServletContextForTemplateLoading()方法放入到web文件夹下
        config.setClassForTemplateLoading(this.getClass(), "/templates");
        //设置异常处理器 这样的话 即使没有属性也不会出错 如：${list.name}...不会报错
        config.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
        config.setDefaultEncoding("UTF-8");
        try {
            if(templateName.endsWith(".ftl")) {
                templateName = templateName.substring(0, templateName.indexOf(".ftl"));
            }
            Template template = config.getTemplate(templateName + ".ftl");
            File outFile = null;

            //创建一个文件路径，用来存放生成的相关文件

            File myFilePath=new File(filePath);
            if(!myFilePath.exists()){
                myFilePath.mkdir();
            }

            //创建新文件

            template = config.getTemplate(templateName + ".ftl","UTF-8");
            outFile=new File(myFilePath+"/"+fileName);

            Writer out = null;
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
            // 生成文件
            template.process(dataMap, out);


            System.out.println("由模板文件：" + templateName + ".ftl" + " 生成Word文件 " + fileName + " 成功！！");
            out.flush();
            out.close();


            //轉換pdf
            String docPath = filePath+fileName;
            String pdfPath = filePath+pdfName;
            Word2PdfAsposeUtil.doc2pdf(docPath,pdfPath);
            File file = new File(pdfPath);
            FileUtil.downloadFile(request,response,file,false);

            File fileWord = new File(docPath);
            /*fileWord.delete();
            file.delete();*/

        } catch (TemplateNotFoundException e) {
            System.out.println("模板文件未找到");
            e.printStackTrace();
        } catch (MalformedTemplateNameException e) {
            System.out.println("模板类型不正确");
            e.printStackTrace();
        } catch (TemplateException e) {
            System.out.println("填充模板时异常");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("IO异常");
            e.printStackTrace();
        }
    }

    public static String getCurrTimeReturnDX() {
        Date d = new Date();

        String dateNowStr = sdf_dx.format(d);
        return dateNowStr;
    }

    public static String getCurrTime() {
        Date d = new Date();

        String dateNowStr = sdf.format(d);
        return dateNowStr;
    }

    public final static char[] upper = "零一二三四五六七八九十".toCharArray();
    /**
     * 根据小写数字格式的日期转换成大写格式的日期
     * @param date
     * @return
     */
    public static String getUpperDate(String date) {
        //支持yyyy-MM-dd、yyyy/MM/dd、yyyyMMdd等格式
        if(date == null) return null;
        //非数字的都去掉
        date = date.replaceAll("\\D", "");
        if(date.length() != 8) return null;
        StringBuilder sb = new StringBuilder();
        for (int i=0;i<4;i++) {//年
            sb.append(upper[Integer.parseInt(date.substring(i, i+1))]);
        }
        sb.append("年");//拼接年
        int month = Integer.parseInt(date.substring(4, 6));
        if(month <= 10) {
            sb.append(upper[month]);
        } else {
            sb.append("十").append(upper[month%10]);
        }
        sb.append("月");//拼接月

        int day = Integer.parseInt(date.substring(6));
        if (day <= 10) {
            sb.append(upper[day]);
        } else if(day < 20) {
            sb.append("十").append(upper[day % 10]);
        } else {
            sb.append(upper[day / 10]).append("十");
            int tmp = day % 10;
            if (tmp != 0) sb.append(upper[tmp]);
        }
        sb.append("日");//拼接日
        return sb.toString();
    }

    public static String readTxtFile(String filePath){
        String lineTxt = null;
        try {
            String encoding="GBK";
            File file=new File(filePath);
            if(file.isFile() && file.exists()){ //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file),encoding);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);

                while((lineTxt = bufferedReader.readLine()) != null){

                    System.out.println(lineTxt);
                    return lineTxt;
                }

                read.close();
            }else{
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return lineTxt;
    }
}
